package com.xiaoxin.experience.util;

import java.lang.management.ManagementFactory;
import java.net.ServerSocket;

/**
 * @author xiaoxin
 */
public class SystemUtil
{

    private SystemUtil(){}

    public static boolean isLinux()
    {
        String property = System.getProperty("os.name");
        return StringUtil.isNotBlank(property) && property.toLowerCase().contains("linux");
    }

    public static String pid()
    {
        String name = ManagementFactory.getRuntimeMXBean().getName();
        return name.split("@")[0];
    }

    public static int cpuCore()
    {
        return Runtime.getRuntime().availableProcessors();
    }

    public static int getAvailablePortSpecFrom(int from)
    {
        for (;from < 65535; from++)
        {
            if (isAvailablePortInNormalRange(from))
            {
                return from;
            }
        }
        throw new RuntimeException("not found available port");
    }

    public static int getAvailablePort(int specPort)
    {
        if (isAvailablePort(specPort))
        {
            return specPort;
        }
        for(int i = 2000; i < 65535; i++)
        {
            if (isAvailablePortInNormalRange(i))
            {
                return i;
            }
        }
        throw new RuntimeException("not found available port");
    }

    public static boolean isAvailablePort(int specPort)
    {
        if (specPort > 0 && specPort < 65535)
        {
            return isAvailablePortInNormalRange(specPort);
        }
        return false;
    }

    private static boolean isAvailablePortInNormalRange(int specPort)
    {
        try (ServerSocket serverSocket = new ServerSocket(specPort))
        {
            serverSocket.getLocalPort();
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
    }
}
